<?php
require_once LIBS_DIR . 'classes/class.Database.php'; //LIBS_DIR is defined in config.php
require_once LIBS_DIR . 'functions.php';


class DataSource extends Database 
{
	private $num_rows = NULL; //amount of rows in sql result
	private $values = array();
	
	public function __construct()
	{
		parent::__construct();
	}
	
	public function sql_query($query)
	{
		$this->query($query);
	}
	
	public function select($from, $where = ' 1 ', $fields = ' * ',  $orderby = '' )
	{
		if (empty($where))  $where = ' 1 ';
		if (empty($fields))  $fields = ' * ';
		$query = 'SELECT ' .$fields. ' FROM ' .$from. ' WHERE ' .$where . ' ';
		if (!empty($orderby)) {
			$query .= ' ORDER BY ' .$orderby. ' ';
		};
// 		echo "<pre>";
// 		print_r($query);
// 		echo "</pre>";
		$this->query($query);
		$this->num_rows = mysql_num_rows($this->result);
		return $this->num_rows;
	}
	
	public function insert($table, $arrayFieldValues)
	{
		$fields = array_map('add_sql_slashes', array_keys($arrayFieldValues));
		$values = array_values($arrayFieldValues);
		
		$escVals = array();
		foreach($values as $val)
		{
			if(!is_numeric($val)){
				$val = "'" .dbsafe($val). "'";
			}
			$escVals[] = $val;
		}
		
		$query = ' INSERT INTO `' .$this->dbprefix.$table. '` (';
		$query .= join(', ', $fields);
		$query .= ') VALUES (';
		$query .= join(', ', $escVals);
		$query .= ')';
		
		$this->query($query);
	}
	
	public function update($table, $arrayFieldValues, $arrayConditions)
	{
		// Forms SET parameter
		$arrayUpdates = array();
		foreach ($arrayFieldValues as $field => $value)
		{
			if(!is_numeric($value)){
				$value = "'" .dbsafe($value). "'";
			}
			$arrayUpdates[] = add_sql_slashes($field) . "= $value";
		}
		
		// Forms WHERE parameter
		$arrayWhere = array();
		foreach ($arrayConditions as $field => $value)
		{
			if(!is_numeric($value)){
				$value = "'" .dbsafe($value). "'";
			}
			$arrayWhere[] = add_sql_slashes($field) . "= $value";
		}
		
		$query  = ' UPDATE `' .$this->dbprefix.$table. '` SET ';
		$query .= join(', ', $arrayUpdates);
		$query .= ' WHERE ' . join(' AND', $arrayWhere);

		$this->query($query);
	}
	
	public function delete($table, $arrayConditions)
	{
		// Forms WHERE parameter
		$arrayWhere = array();
		foreach ($arrayConditions as $field => $value)
		{
			if(!is_numeric($value)){
				$value = "'" .dbsafe($value). "'";
			}
			$arrayWhere[] = add_sql_slashes($field) . "= $value";
		}
		
		$query  = ' DELETE FROM `'. $this->dbprefix.$table. '` WHERE ' . join(' AND', $arrayWhere);

		$this->query($query); 
	}
	
	
	public function next()
	{
		unset($this->values);
		$this->values = $this->fetch();
		
		if (is_array($this->values)){
			foreach ($this->values as $field => $value) {
				$this->values[$field] = stripslashes($value);
			}
		}
		return($this->values);
	}
	
	public function __destruct()
	{
		parent::__destruct();
	}
}

?>